package com.marchsoft.service.impl;

import com.marchsoft.common.enums.ExceptionEnum;
import com.marchsoft.common.exception.CommonException;
import com.marchsoft.common.status.ActivityStatu;
import com.marchsoft.common.utils.TimeUtils;
import com.marchsoft.dao.ActivityMapper;
import com.marchsoft.dao.StudentMapper;
import com.marchsoft.domain.Activity;
import com.marchsoft.domain.Student;
import com.marchsoft.service.IActivityService;
import com.marchsoft.vo.UnDoMsg;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.LinkedList;
import java.util.List;

/**
 * class description：
 * author：rsw
 * Date: 2019/11/17
 * Time: 10:47
 **/
@Service
public class ActivityServiceImpl implements IActivityService {

    @Resource
    private ActivityMapper activityMapper;

    @Resource
    private StudentMapper studentMapper;


    /**
     * 导师处理学生的申请
     *
     * @param sid    学生id
     * @param tid    导师id
     * @param status 22为同意、23为拒绝
     * @return boolean
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertApplyingTeacher(Integer sid, Integer tid, Integer status) {
        /*
            在activity表中增加活动状态
         */
        Activity activity = new Activity();
        activity.setSid(sid);
        activity.setTid(tid);
        if (status == ActivityStatu.STUDENT_APPLIED_TEACHER) {
            //导师选择申请（学生申请导师成功）
            activity.setStatus(ActivityStatu.STUDENT_APPLIED_TEACHER);
            //如果申请成功，在学生表中更改tid字段
            Student student = new Student();
            student.setSid(sid);
            student.setTid(tid);
            studentMapper.updateByPrimaryKeySelective(student);
        } else if (status == ActivityStatu.STUDENT_APPLY_FAIL_TEACHER) {
            //导师选择拒绝（学生申请导师失败）
            activity.setStatus(ActivityStatu.STUDENT_APPLY_FAIL_TEACHER);
        } else {
            //如果不是22或者23，则抛出异常
            throw new CommonException(ExceptionEnum.STUDENT_APPLYING_TEACHER_ERROR);
        }
        //新增记录数为1，则返回true，说明执行成功
        return activityMapper.insertSelective(activity) == 1;
    }

    /**
     * 兴趣小组处理学生的申请
     *
     * @param sid    学生id
     * @param gid    导师id
     * @param status 2为同意、3为拒绝
     * @return boolean
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertApplyingGroup(Integer sid, Integer gid, Integer status) {
        /*
            在activity表中增加活动状态
         */
        Activity activity = new Activity();
        activity.setSid(sid);
        activity.setTid(gid);
        if (status == ActivityStatu.STUDENT_APPLIED_GROUP) {
            //兴趣小组允许申请（学生申请导师成功）
            activity.setStatus(ActivityStatu.STUDENT_APPLIED_GROUP);
            //如果申请成功，在学生表中更改tid字段
            Student student = new Student();
            student.setSid(sid);
            student.setGroupId(gid);
            studentMapper.updateByPrimaryKeySelective(student);
        } else if (status == ActivityStatu.STUDENT_APPLY_FAIL_GROUP) {
            //兴趣小组选择拒绝（学生申请导师失败）
            activity.setStatus(ActivityStatu.STUDENT_APPLY_FAIL_GROUP);
        } else {
            //如果不是2或者3，则抛出异常
            throw new CommonException(ExceptionEnum.STUDENT_APPLYING_GROUP_ERROR);
        }
        //新增记录数为1，则返回true，说明执行成功
        return activityMapper.insertSelective(activity) == 1;
    }

    @Override
    public List<UnDoMsg> queryUnDoMsg(Integer tid, Integer type) {
        List<UnDoMsg> teaApply = activityMapper.queryTeaApply(tid, type);
        List<UnDoMsg> groApply = activityMapper.queryGroApply(tid, type);
        List<UnDoMsg> list = new LinkedList();
        if (teaApply != null) {
            list.addAll(teaApply);
        }
        if (groApply != null) {
            list.addAll(groApply);
        }
        for (UnDoMsg a :
                list) {
            System.out.println(a);
        }
        return teaApply;
    }

    @Override
    public Integer quitTeacher(Integer sid) {
        Student stu = studentMapper.selectByPrimaryKey(sid);
        Activity activity = new Activity();
        if (stu.getTid() != null || stu == null) {
            activity.setTid(stu.getTid());
            activity.setSid(sid);
            activity.setStatus(ActivityStatu.STUDENT_EXITING_TEACHER);
//            activity.setATime(new Timestamp(TimeUtils.getNewStamep()));
//            activity.setIsDelete(1);
//            activityMapper.insert(activity);
            activityMapper.insertSelective(activity);
            return 1;
        } else {
            System.out.println("你还没有导师");
            return 2;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer handleQuitTeacher(Integer sid, Integer statu) {
        Student stu = studentMapper.selectByPrimaryKey(sid);
        System.out.println("触发了");
        //查询是否存在申请退出的情况
        Example example = new Example(Activity.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("tid", stu.getTid());
        criteria.andEqualTo("sid", sid);
        criteria.andEqualTo("isDelete", 1);
        criteria.andEqualTo("status", ActivityStatu.STUDENT_EXITING_TEACHER);
        List<Activity> activities = activityMapper.selectByExample(example);

        //不存在返回2说明错误
        if (activities == null || activities.size() == 0 || activities.size() > 1) {
            return 2;
        } else {
            //存在
            //更新申请退出为已读
            Activity activity = activities.get(0);
            activity.setIsDelete(0);
            activityMapper.updateByPrimaryKey(activity);

            //创建新的activity
            activity.setHdid(null);
            activity.setATime(new Timestamp(TimeUtils.getNewStamep()));
            activity.setIsDelete(1);
            //如果（statu==1 说明接受退出 ==2为不接受）
            if (statu==1){
                //接受
                activity.setStatus(ActivityStatu.STUDENT_EXIT_TEACHER);
                activityMapper.insert(activity);

                //修改原student的导师为0
                stu.setTid(0);
                studentMapper.updateByPrimaryKey(stu);
            }else if(statu==2){
                //拒绝
                activity.setStatus(ActivityStatu.STUDENT_EXIT_FAIL_TEACHER);
                activityMapper.insert(activity);
            }
            return 1;
        }
    }


}

